package com.ruoyi.wechat.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.wechat.common.ServiceException;
import com.ruoyi.wechat.domain.AppUser;
import com.ruoyi.wechat.domain.UserAddr;
import com.ruoyi.wechat.domain.vo.AjaxResult;
import com.ruoyi.wechat.service.IUserAddrService;
import com.ruoyi.wechat.utils.LoginHelper;
import org.apache.http.HttpStatus;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

import static com.ruoyi.wechat.domain.vo.AjaxResult.success;

/**
 * <p>
 * 用户地址
 * </p>
 *
 * @author YinHeng
 * @since 2024/1/19
 */
@RestController
@RequestMapping("/userAddr")
public class UserAddrController {

    @Resource
    private IUserAddrService userAddressService;


    /**
     * 获取个人地址详情
     *
     * @param id
     * @return
     */
    @GetMapping("/detail")
    public AjaxResult detail(Long id) {
        UserAddr detail = userAddressService.detail(id);
        return AjaxResult.success(detail);
    }

    /**
     * 用户地址列表
     */
    @GetMapping("/list")
    public AjaxResult list(UserAddr form) {
        AppUser appUser = LoginHelper.getSession().getAppUser();
        LambdaQueryWrapper<UserAddr> query = new LambdaQueryWrapper<>();
        query.eq(UserAddr::getUserId, appUser.getId());
        List<UserAddr> list = userAddressService.list(query);
        for (UserAddr addr : list) {
            addr.setTitle(addr.getComy() + addr.getRidgepole() + addr.getDoor());
        }
        return success(list);
    }

    /**
     * 新增个人地址
     *
     * @param form
     * @return
     */
    @PostMapping
    public AjaxResult add(@RequestBody UserAddr form) {
        userAddressService.add(form);
        return AjaxResult.success();
    }

    /**
     * 更新个人地址
     *
     * @param form
     * @return
     */
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated(UserAddr.edit.class) UserAddr form) {
        userAddressService.edit(form);
        return AjaxResult.success();
    }

    /**
     * 删除指定id地址
     *
     * @param form
     * @return
     */
    @DeleteMapping
    public AjaxResult delete(@RequestBody UserAddr form) {
        if (ObjectUtils.isEmpty(form.getId())) {
            throw new ServiceException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "参数id为空");
        }
        userAddressService.delete(form.getId());
        return AjaxResult.success();
    }

    /**
     * 设置默认地址
     *
     * @param form
     * @return
     */
    @PutMapping("/set-first")
    public AjaxResult setFirst(@RequestBody UserAddr form) {
        AppUser appUser = LoginHelper.getSession().getAppUser();
        userAddressService.setFirst(appUser.getId(), form.getId());
        return AjaxResult.success();
    }


}
